package app

import (
	// "fmt"
	// "time"

	"github.com/go-apibox/api"
	"github.com/go-apibox/filter"
	"github.com/go-apibox/utils"
)

func ActionDeviceList(c *api.Context) interface{} {
	params := c.NewParams()
	params.AddPagination().AddOrderBy("CreateTime", "desc", []string{"CreateTime"}, false)
	params.Add("LatestConnect", filter.EmptyToNil(), filter.TimeRange())
	params.Add("DeviceGroupId", filter.EmptyToNil(), filter.Uint32())
	params.Add("DeviceGroupName", filter.EmptyToNil(), filter.String())
	params.Add("DeviceId", filter.EmptyToNil(), filter.Uint32())
	params.Add("Name", filter.EmptyToNil(), filter.String())
	params.Add("Code", filter.EmptyToNil(), filter.String())
	params.Add("Status", filter.EmptyToNil(), filter.String())
	if apiErr := params.Parse(); apiErr != nil {
		return apiErr
	}

	list := make([]*DeviceWithGroup, 0, 10)
	return api.ListJoin(c, &list, params, map[string]string{
		"DeviceGroupName": "table:device_group",
		"DeviceGroupId":   "table:device",
		"Name":            "like",
		"Code":            "like",
	},
		[][]string{
			[]string{"INNER", "device_group", "device_group.device_group_id=device.device_group_id"},
		},
	)
}

func ActionDeviceCreate(c *api.Context) interface{} {
	params := c.NewParams()
	params.Add("DeviceGroupId", filter.EmptyToNil(), filter.Required(), filter.Uint32())
	params.Add("Name", filter.EmptyToNil(), filter.String())
	params.Add("Code", filter.EmptyToNil(), filter.String())
	params.Add("Desc", filter.EmptyToNil(), filter.String())
	params.Add("Otg", filter.EmptyToNil(), filter.String())
	params.Add("Ip", filter.EmptyToNil(), filter.String())
	params.Add("Port", filter.EmptyToNil(), filter.String())
	// params.Add("Status", filter.EmptyToNil(), filter.String())
	if apiErr := params.Parse(); apiErr != nil {
		return apiErr
	}
	dgId := params.GetUint32("DeviceGroupId")
	dg := new(DeviceGroup)
	has, err := app.engine.Where("device_group_id=?", dgId).Get(dg)
	if err != nil {
		app.logger.Error(err)
		return c.Error.New(api.ErrorInvalidParam, "DeviceGroupId")
	}
	if !has {
		return c.Error.New(api.ErrorInvalidParam, "DeviceGroupId")
	}

	dg.DeviceCount++
	app.engine.Where("device_group_id=?", dgId).Cols("device_count").Update(dg)

	params.Set("Status", USER_STATUS_NORMAL)

	device := new(Device)
	data := api.Create(c, device, params)
	if !api.IsError(data) {
		// 给设备添加任务
		tmpTaskLog := new(TaskLog)
		has, err = app.engine.Where("device_group_id=?", dgId).And("status=?", TASK_STATUS_UNDO).Get(tmpTaskLog)
		if err != nil {
			app.logger.Error(err)
			return data
		}
		if !has {
			app.logger.Debug("1")
			return data
		}
		app.logger.Debugf("%+v\n", tmpTaskLog)
		tls := make([]*TaskLog, 0, 100)
		if err := app.engine.Where("device_id=?", tmpTaskLog.DeviceId).And("status=?", TASK_STATUS_UNDO).Find(&tls); err != nil {
			app.logger.Error(err)
			return data
		}
		if len(tls) == 0 {
			app.logger.Debug("is empyt ")
			return data
		}
		for _, tl := range tls {
			tl.DeviceId = device.DeviceId
			tl.DeviceCode = device.Code
			tl.DeviceName = device.Name
			tl.TaskLogId = utils.RandUint64()
		}

		app.logger.Debug("2", len(tls))

		if _, err := app.engine.Insert(tls); err != nil {
			app.logger.Debug(err)
		}

	}
	return data
}

func ActionDeviceUpdate(c *api.Context) interface{} {
	params := c.NewParams()
	params.Add("DeviceGroupId", filter.EmptyToNil(), filter.Required(), filter.Uint32())
	params.Add("DeviceGroupName", filter.EmptyToNil(), filter.String())
	params.Add("Desc", filter.EmptyToNil(), filter.String())
	if apiErr := params.Parse(); apiErr != nil {
		return apiErr
	}
	return api.Update(c, new(DeviceGroup), params)
}

func ActionDeviceDetail(c *api.Context) interface{} {
	params := c.NewParams()
	params.Add("DeviceId", filter.EmptyToNil(), filter.Required(), filter.Uint32())
	if apiErr := params.Parse(); apiErr != nil {
		return apiErr
	}
	return api.Detail(c, new(Device), params)
}

func ActionDeviceDelete(c *api.Context) interface{} {
	params := c.NewParams()
	params.Add("DeviceId", filter.EmptyToNil(), filter.Required(), filter.Uint32())
	if apiErr := params.Parse(); apiErr != nil {
		return apiErr
	}

	return api.Delete(c, new(Device), params)
}
